/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  TempReportActivity.java   
 * @Package com.jiyi.activity.new_maintenance   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-4 下午2:10:00   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.maintenance.RepairEquipItem;
import com.jiyi.bean.maintenance.RepairFirstEquip;
import com.jiyi.bean.maintenance.RepairSecondEquip;
import com.jiyi.bean.maintenance.RepairTask.RepairTaskItem;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.RepairTaskListEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: TempReportActivity
 * @Description:TODO(临检报表)
 * @author: HYM
 * @date: 2017-9-4 下午2:10:00
 * 
 */
public class TempReportWriteActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;
	
	/* activity控件 */
	@BindView(R.id.state_first)
	Spinner state_first;
	@BindView(R.id.state_second)
	Spinner state_second;
	@BindView(R.id.state_equip_point)
	Spinner state_equip_point;
	@BindView(R.id.etNo)
	EditText etNo;
	@BindView(R.id.etPosition)
	EditText etPosition;
	@BindView(R.id.etDescribe)
	EditText etDescribe;
	@BindView(R.id.etRecord)
	EditText etRecord;
	@BindView(R.id.etProductName)
	EditText etProductName;
	@BindView(R.id.etBrand)
	EditText etBrand;
	@BindView(R.id.et_create)
	EditText et_create;
	@BindView(R.id.et_replace)
	EditText et_replace;
	@BindView(R.id.etModel)
	EditText etModel;
	@BindView(R.id.state_equip)
	Spinner state_equip;
	@BindView(R.id.etPrice)
	EditText etPrice;
	@BindView(R.id.etRepairPrice)
	EditText etRepairPrice;
	@BindView(R.id.state_payer)
	Spinner state_payer;
	@BindView(R.id.llProduct)
	LinearLayout llProduct;
	
	//设备状态，付款方适配器,
	ArrayAdapter<String> stateEquipAdapter,statePayerAdapter,stateCheckAdapter;
	CommonAdapter<RepairFirstEquip> stateFirstAdapter;
	CommonAdapter<RepairSecondEquip> stateSecondAdapter;
	CommonAdapter<RepairEquipItem> stateEquipPointAdapter;
	//设备id,付款方id,进度id
	String stateEquipId="",statePayerId="";
	//接受传递过来的值，公司Id,详情id
	String companyId="",id="";
	//列表类型，父集合的位置
	int type ,position;
	//进度条
	Dialog dialog;
	List<RepairFirstEquip> firstDataList = new ArrayList<RepairFirstEquip>();
	List<RepairSecondEquip> secondDataList = new ArrayList<RepairSecondEquip>();
	List<RepairEquipItem> equipPointDataList = new ArrayList<RepairEquipItem>();
	//是否展开产品详情
	boolean isExtendProduct = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_temp_report_write);
		ButterKnife.bind(this);

		init();

	}

	private void init() {
		getIntentData();
		setTop();
		setViewStatus();
		setAdapter();
		getFirst();
	}
	
	private void getIntentData() {
		Intent intent = getIntent();
		id = intent.getStringExtra("id");
		companyId = intent.getStringExtra("companyId");
		type = intent.getIntExtra("type", 0);
		position = intent.getIntExtra("position", 0);
	}

	private void setTop() {
		tvTitle.setText("填写临检报表");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("取消");
	}
	
	private void setViewStatus() {
		//设置日期控件不能输出
		et_create.setKeyListener(null);
		
		//设置必填项检测提示
		state_first.setTag(R.id.tag_view_empty, "一级不能为空");
		state_second.setTag(R.id.tag_view_empty, "二级不能为空");
		state_equip_point.setTag(R.id.tag_view_empty, "设备项不能为空");
		state_payer.setTag(R.id.tag_view_empty, "设备项不能为空");
		etPosition.setTag(R.id.tag_view_empty, "设备位置不能为空");
		etDescribe.setTag(R.id.tag_view_empty, "故障描述不能为空");
		etRecord.setTag(R.id.tag_view_empty, "实测记录不能为空");
		etNo.setTag(R.id.tag_view_empty, "设备编号不能为空");
		et_create.setTag(R.id.tag_view_empty, "生产日期不能为空");
		et_replace.setTag(R.id.tag_view_empty, "保持日期不能为空");
		etProductName.setTag(R.id.tag_view_empty, "产品名称不能为空");
		etBrand.setTag(R.id.tag_view_empty, "产品品牌不能为空");
		etModel.setTag(R.id.tag_view_empty, "设备型号不能为空");
		etPrice.setTag(R.id.tag_view_empty, "单价不能为空");
		etRepairPrice.setTag(R.id.tag_view_empty, "维修金额不能为空");
		state_equip.setTag(R.id.tag_view_empty, "设备状态不能为空");
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.tvPost,R.id.rlMoreProduct,R.id.et_create })
	public void onClick(View view) {
		DateChooseDialog.Builder builder;
		switch (view.getId()) {
		case R.id.tvBack:
		case R.id.tvSearch:
			finish();
			break;
		case R.id.tvPost:
			//提交
			if (CheckUtil.checkView(state_first,state_second,state_equip_point,etPosition,etDescribe,etRecord,etNo,etProductName,etBrand,et_create,et_replace,etModel,state_equip,etPrice,etRepairPrice)) {
				doPost();
			}
			break;
		case R.id.et_create:
			//生产日期
			builder = new DateChooseDialog.Builder(this,et_create.getText().toString());
			builder.setTitle("选择日期");  
			builder.setTextView(et_create);
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
				public void onClick(DialogInterface dialog, int which) {  
					dialog.dismiss();  						
				}
			});
			
			builder.setNegativeButton("取消",  
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {  
					dialog.dismiss();  
				}  
			});  
			builder.create().show();
			break;
		case R.id.rlMoreProduct:
			if (isExtendProduct) {
				llProduct.setVisibility(View.GONE);
				isExtendProduct = false;
			}
			else {
				llProduct.setVisibility(View.VISIBLE);
				isExtendProduct = true;
			}
			break;
		default:
			break;
		}
	}
	
	private void setAdapter() {
		resetFirst();
		stateFirstAdapter = new CommonAdapter<RepairFirstEquip>(this, firstDataList, R.layout.item_spinner) {

			@Override
			public void convert(ViewHolder holder, RepairFirstEquip t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		state_first.setAdapter(stateFirstAdapter);
		state_first.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				RepairFirstEquip temp = (RepairFirstEquip) parent.getAdapter().getItem(position);
				state_first.setTag(R.id.tag_view_select_value, temp.getCom_ins_id());
				resetSecond();
				resetEquipPoint();
				//做个判断，如果上级菜单传给我们的是空id，即上级未选择选项，则我们不去获取下级的菜单
				if (!TextUtils.isEmpty(firstDataList.get(position).getId())) {
					getSecond(firstDataList.get(position).getCom_ins_id());
				}
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		
		resetSecond();
		stateSecondAdapter = new CommonAdapter<RepairSecondEquip>(this, secondDataList, R.layout.item_spinner) {

			@Override
			public void convert(ViewHolder holder, RepairSecondEquip t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		state_second.setAdapter(stateSecondAdapter);
		state_second.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				RepairSecondEquip temp = (RepairSecondEquip) parent.getAdapter().getItem(position);
				state_second.setTag(R.id.tag_view_select_value, temp.getTask_equip_id());
				resetEquipPoint();
				//做个判断，如果上级菜单传给我们的是空id，即上级未选择选项，则我们不去获取下级的菜单
				if (!TextUtils.isEmpty(secondDataList.get(position).getTask_equip_id())) {
					getEquipPoint(secondDataList.get(position).getTask_equip_id());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		
		resetEquipPoint();
		stateEquipPointAdapter = new CommonAdapter<RepairEquipItem>(this, equipPointDataList, R.layout.item_spinner) {

			@Override
			public void convert(ViewHolder holder, RepairEquipItem t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		state_equip_point.setAdapter(stateEquipPointAdapter);
		state_equip_point.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				RepairEquipItem temp =  (RepairEquipItem) parent.getAdapter().getItem(position);
				state_equip_point.setTag(R.id.tag_view_select_value, temp.getId());
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});	
		
		stateEquipAdapter = new ArrayAdapter<String>(this,R.layout.item_spinner, getResources().getStringArray(R.array.equip_state));
		state_equip.setAdapter(stateEquipAdapter);
		state_equip.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				stateEquipId = getStateEquipId(position);
				state_equip.setTag(R.id.tag_view_select_value, stateEquipId);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});	
		
		statePayerAdapter = new ArrayAdapter<String>(this,R.layout.item_pop_list, getResources().getStringArray(R.array.payer_state));
		state_payer.setAdapter(statePayerAdapter);
		state_payer.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				statePayerId = getStatePayerId(position);
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});		
		
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getFirst   
	 * @Description: TODO(得到一级设备的列表)    void 
	 * @date: 2017-5-11
	 */  
	private void getFirst()
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", companyId);
		
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_REPAIR_FIRST_EQUIP, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<RepairFirstEquip> temp = new Gson().fromJson(data, new TypeToken<List<RepairFirstEquip>>() {}.getType());
								if (temp.size() > 0) {
									firstDataList.addAll(temp);
									stateFirstAdapter.notifyDataSetChanged();
								}
							}
							else {
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finally
						{
							hideDialog(dialog);
						}
						
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
					}
				});
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getFirst   
	 * @Description: TODO(得到一级设备的列表)    void 
	 * @date: 2017-5-11
	 */  
	private void getSecond(String id)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", companyId);
		params.put("id", id);
		
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_REPAIR_SECOND_EQUIP, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<RepairSecondEquip> temp = new Gson().fromJson(data, new TypeToken<List<RepairSecondEquip>>() {}.getType());
								if (temp.size() > 0) {
									resetSecond();
									secondDataList.addAll(temp);
									stateSecondAdapter.notifyDataSetChanged();
								}
							}
							else {
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finally
						{
							hideDialog(dialog);
						}
						
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
					}
				});
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getFirst   
	 * @Description: TODO(得到设备点位的列表)    void 
	 * @date: 2017-5-11
	 */  
	private void getEquipPoint(String id)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_REPAIR_EQUIP_ITEM, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<RepairEquipItem> temp = new Gson().fromJson(data, new TypeToken<List<RepairEquipItem>>() {}.getType());
								if (temp.size() > 0) {
									resetEquipPoint();
									equipPointDataList.addAll(temp);
									stateEquipAdapter.notifyDataSetChanged();
								}
							}
							else {
								
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finally
						{
							hideDialog(dialog);
						}
						
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
					}
				});
	}
	
	/**   
	 * @author: HYM 
	 * @Title: doPost   
	 * @Description: TODO(执行填单)   
	 * @param:       
	 * @return: void       
	 * @throws   
	 */  
	private void doPost() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("sec_equipId", new Gson().fromJson(state_second.getSelectedItem().toString(), RepairSecondEquip.class).getTask_equip_id());
		params.put("fir_equipId", new Gson().fromJson(state_first.getSelectedItem().toString(), RepairFirstEquip.class).getCom_ins_id() );
		params.put("name_equip", new Gson().fromJson(state_equip_point.getSelectedItem().toString(), RepairEquipItem.class).getId());
		params.put("bid", id);
		params.put("content", etDescribe.getText().toString());
		params.put("place", etPosition.getText().toString());
		params.put("record", etRecord.getText().toString());
		params.put("amount", etRepairPrice.getText().toString());
		params.put("price", etPrice.getText().toString());
		params.put("pro_name", etProductName.getText().toString());
		params.put("product", etBrand.getText().toString());
		params.put("pro_type", etModel.getText().toString());
		params.put("pro_date", et_create.getText().toString());
		params.put("pro_safe_date", et_replace.getText().toString());
		params.put("bh_code", etNo.getText().toString());
		params.put("payer", statePayerId);
		params.put("equip_status", stateEquipId);
		
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_REPAIR_TEMP_UPLOAD, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								JSONObject dataJson = new JSONObject(data);
								String bdid = dataJson.getString("bdid");
								
								ToastUtil.getInstances().showMsg(info);
//								setResult(RESULT_OK);
								RepairTaskItem temp = new RepairTaskItem();
								temp.setId(bdid);
								EventBus.getDefault().post(new RepairTaskListEvent(type,position,temp,2));
								finish();
							}
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finally
						{
							hideDialog(dialog);
						}
						
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
	
	
	
	/**   
	 * @author: HYM 
	 * @Title: getStateEquipId   
	 * @Description: TODO(获取设备状态)   
	 * @param: @param position
	 * @param: @return      
	 * @return: String       
	 * @throws   
	 */  
	public String getStateEquipId(int position)
	{
		return position == 0 ? "" : String.valueOf(position-1);
	}
	 
	/**   
	 * @author: HYM 
	 * @Title: setStateEquipId   
	 * @Description: TODO(根据状态id来设置选择项)   
	 * @param stateEquip
	 * @return int
	 * @date: 2017-5-8
	 */  
	public int setStateEquipId(String stateEquip)
	{
		if (TextUtils.isEmpty(stateEquip)) {
			return 0;
		}
		else {
			return Integer.parseInt(stateEquip)+1;
		}
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getStatePayerId   
	 * @Description: TODO(获取付款方)   
	 * @param: @param position
	 * @param: @return      
	 * @return: String       
	 * @throws   
	 */  
	public String getStatePayerId(int position) {
		return String.valueOf(position);
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: resetFirst   
	 * @Description: TODO(初始化一级菜单列表)    void 
	 * @date: 2017-5-11
	 */  
	private void resetFirst()
	{
		firstDataList.clear();
		RepairFirstEquip head = new RepairFirstEquip();
		head.setId("");
		head.setName("请选择");
		firstDataList.add(head);
	}
	
	/**   
	 * @author: HYM 
	 * @Title: resetSecond   
	 * @Description: TODO(初始化二级菜单列表)    void 
	 * @date: 2017-5-11
	 */  
	private void resetSecond() {
		secondDataList.clear();
		RepairSecondEquip secondHead = new RepairSecondEquip();
		secondHead.setTask_equip_id("");
		secondHead.setName("请选择");
		secondDataList.add(secondHead);		
		if (stateSecondAdapter != null) {
			stateSecondAdapter.notifyDataSetChanged();
		}
	}
	
	/**   
	 * @author: HYM 
	 * @Title: resetSecond   
	 * @Description: TODO(初始化设备点位列表)    void 
	 * @date: 2017-5-11
	 */  
	private void resetEquipPoint() {
		equipPointDataList.clear();
		RepairEquipItem equipPointHead = new RepairEquipItem();
		equipPointHead.setName("请选择");
		equipPointHead.setId("");
		equipPointDataList.add(equipPointHead);		
		if (stateEquipPointAdapter != null) {
			stateEquipPointAdapter.notifyDataSetChanged();
		}
	}
}
